package com.ltmonitor.web.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ltmonitor.entity.BasicData;
import com.ltmonitor.entity.VehicleData;
import com.ltmonitor.service.MapFixService;
import com.ltmonitor.util.DateUtil;
import com.ltmonitor.util.StringUtil;
import com.ltmonitor.vo.PaginateResult;
import com.ltmonitor.vo.PointLatLng;
import com.ltmonitor.web.util.JsonMessage;
import com.sun.istack.logging.Logger;

import net.sf.json.JSONObject;

/**
 * 历史轨迹回放
 * 
 * @author DELL
 * 
 */
@Controller
@RequestMapping("/historyGpsInfo")
public class HistoryGpsInfoAction extends PaginateAction {
	org.apache.log4j.Logger debugLog = org.apache.log4j.Logger.getLogger("debug");

	// 打开页面的Action 方法,不做操作，直接打开页面
	public String view() {
		return "view";
	}

	/**
	 * 分页查询终端命令列表
	 * 
	 * @return
	 */
	@RequestMapping("/listByPage.action")
	@ResponseBody
	public PaginateResult execute(
			@RequestParam(value = "page", defaultValue = "1") int page,
			@RequestParam(value = "rows", defaultValue = "10") int rows,
			String plateNo, String fileName, String startTime, String endTime) {
		String queryId = "gpsInfo.selectGpsInfos";
		Map params = this.getParams();
		if (getOnlineUser() != null) {
			params.put("userId", getOnlineUser().getEntityId());
		}
		PaginateResult result = new PaginateResult();
		try {
			long vehicleId = 0;
			if (plateNo != null) {
				VehicleData vd = this.vehicleDataService
						.getVehicleByPlateNo(plateNo);
				if (vd != null)
					vehicleId = vd.getEntityId();
			}

			if (vehicleId == 0 || plateNo == null) {
				log.error("无效车牌号:" + plateNo);
				// resultMap.put("error", plateNo+"没有对应的车辆");
				return result;
			}

			if (page <= 1) {
				this.LogOperation(plateNo + "历史轨迹回放,时间段:" + startTime + "至"
						+ endTime);
			}

			// 单车监控，用于生成监控车辆轨迹

			String queryId1 = "selectStaticVehicleInfo"; // 查询单个车辆的综合信息
			params.put("vehicleId", vehicleId);
			List<Map<String, Object>> vehicleInfoResult = this.queryService
					.query(queryId1, params);
			Map vehicleInfoMap = new HashMap();
			if (vehicleInfoResult.size() > 0) {
				vehicleInfoMap = (Map) vehicleInfoResult.get(0);
				// 转换车牌号数字为文字描述
				this.convert(vehicleInfoMap, "plateColor", "plateColor");
			}
			/**
			startTime = startTime.substring(0, 10).replace("-", "");
			endTime = endTime.substring(0, 10).replace("-", "");
			String today = DateUtil.toStringByFormat(new Date(), "yyyyMMdd");
			if (endTime.compareTo(today) > 0)
				endTime = today;
			String tableName1 = "gpsInfo" + startTime;
			params.put("tableName1", tableName1);
			String tableName2 = "gpsInfo" + endTime;
			params.put("tableName2", tableName2);

			if (tableName1.equals(tableName2) == false) {
				queryId = "selectGpsInfosIn2Days";
			}
			*/
			// params.put("valid", 1);
			result = queryService
					.queryByPagination(queryId, params, page, rows);
			int rowNo = (page - 1) * rows + 1;
			List<Map<String, Object>> mapList = result.getRows();
			int rowCount = 0;
			for (Map<String, Object> rowData : mapList) {
				rowData.putAll(vehicleInfoMap);

				// int rowNum = rowCount + (page - 1) * rows + 1;

				rowData.put("RowNum", rowNo++);

				Double latitude = Double.parseDouble(""
						+ rowData.get("latitude"));
				Double longitude = Double.parseDouble(""
						+ rowData.get("longitude"));
				rowData.put("orgLatitude", latitude);
				rowData.put("orgLongitude", longitude);
				// if (Constants.MAP_BAIDU.equals(this.getUsedMapType())) {
				// pointList.add(new PointLatLng(longitude, latitude));
				// } else {
				// 坐标加偏
				PointLatLng pl = MapFixService.fix(latitude, longitude,
						this.getMapType());
				rowData.put("latitude", pl.getLat());
				rowData.put("longitude", pl.getLng());

				// }

				String valid = "" + rowData.get("valid");
				if ("true".equals(valid)) {
					rowData.put("valid", "有效");
				} else
					rowData.put("valid", "无效");

				int direction = (Integer) rowData.get("direction");
				String directionDescr = this.getDirectionDescr(direction);
				rowData.put("directionDescr", directionDescr);

				int status = (Integer) rowData.get("status");
				String strStatus = Integer.toBinaryString(status);
				strStatus = StringUtil.leftPad(strStatus, 32, '0');
				strStatus = getStatusDescr(strStatus);
				rowData.put("status", strStatus);

				int alarmState = (Integer) rowData.get("alarmState");
				String alarmStateDescr = this.getAlarmDescr(alarmState);
				rowData.put("alarmStateDescr", alarmStateDescr);

			}

		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
			// resultMap.put("error", ex.getMessage());
		}
		return result;
	}

	/**
	 * 分页查询终端命令列表
	 * 
	 * @return
	 */
	@RequestMapping("/list.action")
	@ResponseBody
	public JsonMessage queryWithoutPagination(String plateNo,
			HttpServletRequest request, String startTime, String endTime) {
		String queryId = "gpsInfo.selectGpsInfos";
		Map params = this.getParams();
		if (getOnlineUser() != null) {
			// 只查询用户自己下发的命令
			params.put("userId", getOnlineUser().getEntityId());
		}
		try {
			long vehicleId = 0;
			if (plateNo != null) {
				VehicleData vd = this.vehicleDataService
						.getVehicleByPlateNo(plateNo);
				if (vd != null)
					vehicleId = vd.getEntityId();
			}

			if (vehicleId == 0 || plateNo == null) {
				log.error("无效车牌号:" + plateNo);
				return json(false, plateNo + "没有对应的车辆");
			}

			this.LogOperation(plateNo + "历史轨迹回放,时间段:" + startTime + "至"
					+ endTime);

			// 单车监控，用于生成监控车辆轨迹

			Date start2 = new Date();
			String queryId1 = "vehicle.selectStaticVehicleInfo"; // 查询单个车辆的综合信息
			params.put("vehicleId", vehicleId);
			List<Map<String, Object>> vehicleInfoResult = this.queryService
					.query(queryId1, params);
			Date endDate2 = new Date();
			double min2 = DateUtil.getSeconds(start2, endDate2);
			if (min2 > 2) {
				log.error("查询历史轨迹数据共"+ vehicleInfoResult.size() + "条，耗时:" + min2 + "秒");
			}
			
			Map vehicleInfoMap = new HashMap();
			if (vehicleInfoResult.size() > 0) {
				vehicleInfoMap = (Map) vehicleInfoResult.get(0);
				// 转换车牌号数字为文字描述
				this.convert(vehicleInfoMap, "plateColor", "plateColor");
			}
			/**
			startTime = startTime.substring(0, 10).replace("-", "");
			endTime = endTime.substring(0, 10).replace("-", "");
			String today = DateUtil.toStringByFormat(new Date(), "yyyyMMdd");
			if (endTime.compareTo(today) > 0)
				endTime = today;
			String tableName1 = "gpsInfo" + startTime;
			params.put("tableName1", tableName1);
			String tableName2 = "gpsInfo" + endTime;
			params.put("tableName2", tableName2);

			if (tableName1.equals(tableName2) == false) {
				queryId = "gpsInfo.selectGpsInfosIn2Days";
			}*/

			// params.put("valid", 1);
			List<Map<String, Object>> mapList = this.queryService.query(
					queryId, params);
			int rowNo = 1;
			for (Map<String, Object> rowData : mapList) {
				rowData.putAll(vehicleInfoMap);
				rowData.put("RowNum", rowNo++);

				Double latitude = Double.parseDouble(""
						+ rowData.get("latitude"));
				Double longitude = Double.parseDouble(""
						+ rowData.get("longitude"));
				rowData.put("orgLatitude", latitude);
				rowData.put("orgLongitude", longitude);
				// if (Constants.MAP_BAIDU.equals(this.getUsedMapType())) {
				// pointList.add(new PointLatLng(longitude, latitude));
				// } else {
				// 坐标加偏
				PointLatLng pl = MapFixService.fix(latitude, longitude,
						this.getMapType());
				rowData.put("latitude", pl.getLat());
				rowData.put("longitude", pl.getLng());

				// }

				String valid = "" + rowData.get("valid");
				if ("true".equals(valid)) {
					rowData.put("valid", "有效");
				} else
					rowData.put("valid", "无效");

				int direction = (Integer) rowData.get("direction");
				String directionDescr = this.getDirectionDescr(direction);
				rowData.put("directionDescr", directionDescr);

				int status = (Integer) rowData.get("status");
				String strStatus = Integer.toBinaryString(status);
				strStatus = StringUtil.leftPad(strStatus, 32, '0');
				strStatus = getStatusDescr(strStatus);
				rowData.put("status", strStatus);

				int alarmState = (Integer) rowData.get("alarmState");
				String alarmStateDescr = this.getAlarmDescr(alarmState);
				rowData.put("alarmStateDescr", alarmStateDescr);

			}

			return json(true, mapList);

		} catch (Exception ex) {
			return json(false, ex.getMessage());
		}
	}

	protected String getStatusDescr(String status) {
		StringBuilder sb = new StringBuilder();

		if (StringUtil.isNullOrEmpty(status) == false) {
			char[] ch = status.toCharArray();
			if (ch.length == 32) {
				int m = 31;
				int c = ch[m - 0] - 48;
				sb.append(c == 1 ? "ACC开" : "ACC关").append(",");
				c = ch[m - 1] - 48;
				sb.append(c == 1 ? "定位" : "未定位").append(",");
				c = ch[m - 4] - 48;
				sb.append(c == 1 ? "停运" : "运营").append(",");
				c = ch[m - 10] - 48;
				sb.append(c == 1 ? "油路断开" : "油路正常").append(",");
				c = ch[m - 11] - 48;
				sb.append(c == 1 ? "电路断开" : "电路正常").append(",");
				c = ch[m - 12] - 48;
				sb.append(c == 1 ? "车门加锁" : "车门解锁").append(",");
			}
		}

		return sb.toString();
	}
protected String getDirectionDescr(int direction) {
		String descr = "";
        if (direction == 0)
        {
            descr = "正北";
        }
        else if (direction == 90)
        {
            descr = "正东";
        }
        else if (direction == 180)
        {
            descr = "正南";
        }
        else if (direction == 270)
        {
            descr = "正西";
        }
        else if (direction == 45)
        {
            descr = "东北";
        }
        else if (direction == 135)
        {
            descr = "东南";
        }
        else if (direction == 225)
        {
            descr = "西南";
        }
        else if (direction == 315)
        {
            descr = "西北";
        }
        else if (direction < 90)
        {
            descr = "东偏北" + direction + "度";
        }
        else if (direction > 90 && direction < 180)
        {
            descr = "东偏南" + (direction-90) + "度";
        }
        else if (direction > 180 && direction < 270)
        {
            descr = "西偏南" + (270 - direction) + "度";
        }
        else if (direction > 270 && direction < 360)
        {
            descr = "西偏北" + (direction - 270) + "度";
        }
        return descr;
	}

	/**
	 * 报警描述
	 * 
	 * @param alarm
	 * @return
	 */
	protected String getAlarmDescr(int alarmState) {
		StringBuilder sb = new StringBuilder();
		String alarm = Integer.toBinaryString(alarmState);
		alarm = StringUtil.leftPad(alarm, 32, '0');
		if (StringUtil.isNullOrEmpty(alarm) == false) {
			char[] ch = alarm.toCharArray();
			for (int m = 0; m < ch.length; m++) {
				int tag = Integer.parseInt("" + ch[m]);
				if (tag == 1) {
					int alarmId = 31 - m; // 倒序，转换为部标的报警序号
					BasicData bd = basicDataService.getBasicDataByCode(""
							+ alarmId, "AlarmType");
					if (bd != null) {
						sb.append(bd.getName()).append(",");
					}
				}
			}
		}

		return sb.toString();
	}

	
	
	/**
	 * 获取停车记录数据
	 * @param jsonStr
	 * @return
	 */
	@RequestMapping("/getVehicleStopInfo.action")
	public @ResponseBody JsonMessage getVehicleStopInfo(@RequestBody String jsonStr) {
		JsonMessage result = null;
		try {
			Map<String, Object> map = JSONObject.fromObject(jsonStr);
			String queryId =  "historyRoute.selectVehicleStopInfo";
			List list = this.queryService.query(queryId, map);
			
			result = new JsonMessage(true, list);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			result = new JsonMessage(false, e.getMessage());
		}
		return result;
	}
}
